import logging
import os

import requests
from bs4 import BeautifulSoup
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import transaction
from django.db.models import Q
from django.http import FileResponse
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser, MultiPartParser, FormParser
from rest_framework.utils import json
from rest_framework.views import APIView
from api_test.common.api_loadfile import import_api
from api_test.common.api_response import JsonResponse
from api_test.common.common import record_dynamic
from api_test.models import Project, ApiGroupLevelFirst, ApiInfo, ApiParameter, ApiResponse, ApiVersionLevelFirst, \
    ApiDataType, LoadFile
from api_test.serializers import ApiInfoSerializer, ApiInfoListSerializer, ApiInfoDeserializer, \
    ApiParameterDeserializer, ApiResponseDeserializer, ProjectSerializer, LoadFileSerializer, \
    LoadFileDeSerializer
from fotoable_api_test import settings


logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。


class CoverageList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        """
        获取代码覆盖文件列表
        """
        # 判断是否传分组id，否则为所有接口列表
        page_size = request.GET.get("page_size")
        page = request.GET.get("page")
        base_url = 'http://192.168.203.1:9532/PHPCoverage'
        code_list = []
        content = requests.get(base_url).text
        soup = BeautifulSoup(content, 'html.parser')
        for ul in soup.select('.filelist')[0].select('li'):
            url = ul.select('a')[0].attrs['href']
            if "App-HttpController" in url:
                coverage = ul.select('span')[0].text
                path = f'{base_url}/{url}'
                coverage_list = coverage.split(" ")
                coverage_code = coverage_list[1][1:-1].split("/")
                re = '-data-wwwroot-zhwapp_9533'
                file_name = url.replace(re, "").replace("html", "php").replace("-", "/")
                file_dict = dict()
                file_dict['name'] = file_name
                file_dict['url'] = path
                file_dict['uncoveredLine'] = int(coverage_code[1]) - int(coverage_code[0])
                file_dict['coveredLine'] = coverage_code[0]
                file_dict['codeLine'] = coverage_code[1]
                file_dict['coveredRate'] = coverage_list[0]
                code_list.append(file_dict)
        if page and page_size:
            total = len(code_list)
            if int(page_size) >= total:
                code_list = code_list
            else:
                code_list = code_list[int(page_size) * (int(page) - 1): int(page) * int(page_size)]
            return JsonResponse(data={"data": code_list, "page_sizes": page_size, "total": total, "page": int(page)}, code="999999", msg="成功!")
        else:
            return JsonResponse(data={"data": code_list}, code="999999", msg="成功!")


class CoverageEcharts(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        """
        获取代码覆盖文件列表
        """
        # 判断是否传分组id，否则为所有接口列表
        code_list = []
        html = requests.get('http://192.168.203.1:9532/PHPCoverage')
        html.encoding = 'utf-8'
        soup = BeautifulSoup(html.text, 'html.parser')
        label_list = soup.select('.sum')[0].select('label')
        span_list = soup.select('.sum')[0].select('span')
        unexecute = int(span_list[1].text) - int(span_list[2].text)
        for i in range(5):
            if label_list[i].text in ['覆盖可执行代码行数：', '可执行代码行数：']:
                code_list.append(
                    dict(name=label_list[i].text[:-1], value=span_list[i].text, itemStyle={'color': '#4CB24C'}))
        code_list.append(dict(name='不可执行代码行数', value=str(unexecute), itemStyle={'color': '#997F7F'}))
        code_list.append(dict(name='未覆盖可执行代码行数', value=str(int(code_list[0]['value']) - int(code_list[1]['value'])),
                              itemStyle={'color': '#FF6666'}))
        del code_list[0]
        code_dict = dict()
        code_dict['data'] = code_list
        code_dict['fileCounts'] = span_list[0].text
        code_dict['coverageRate'] = span_list[4].text

        return JsonResponse(data={"data": code_list}, code="999999", msg="成功!")